package com.example.myapplication.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.data.model.ItemWithPath
import com.example.myapplication.data.repository.SearchHistoryRepository
import com.example.myapplication.data.repository.StorageItemRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import javax.inject.Inject

data class SearchUiState(
    val searchQuery: String = "",
    val searchResults: List<ItemWithPath> = emptyList(), // 改为ItemWithPath
    val searchHistory: List<String> = emptyList(),
    val isLoading: Boolean = false,
    val errorMessage: String? = null,
    val hasSearched: Boolean = false // 是否已经进行过搜索
)

@HiltViewModel
class SearchViewModel @Inject constructor(
    private val storageItemRepository: StorageItemRepository,
    private val searchHistoryRepository: SearchHistoryRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(SearchUiState())
    val uiState: StateFlow<SearchUiState> = _uiState.asStateFlow()
    
    private var searchJob: Job? = null // 用于取消之前的搜索任务

    init {
        viewModelScope.launch {
            searchHistoryRepository.searchHistory.collect { history ->
                _uiState.update { it.copy(searchHistory = history) }
            }
        }
    }

    fun onSearchQueryChange(query: String) {
        _uiState.update { it.copy(searchQuery = query) }
        
        // 实时搜索逻辑
        searchJob?.cancel() // 取消之前的搜索任务
        
        if (query.isBlank()) {
            _uiState.update { it.copy(searchResults = emptyList(), hasSearched = false, isLoading = false) }
            return
        }
        
        // 实时搜索，最小长度为1个字符
        if (query.trim().length >= 1) {
            searchJob = viewModelScope.launch {
                delay(300) // 防抖动：300ms延迟
                performRealtimeSearch(query.trim())
            }
        }
    }

    private suspend fun performRealtimeSearch(query: String) {
        _uiState.update { it.copy(isLoading = true) }
        try {
            storageItemRepository.searchItemsWithPath(query).collect { results ->
                _uiState.update {
                    it.copy(
                        searchResults = results,
                        isLoading = false,
                        hasSearched = true,
                        errorMessage = null
                    )
                }
            }
        } catch (e: Exception) {
            _uiState.update {
                it.copy(
                    errorMessage = "搜索失败: ${e.message}",
                    isLoading = false,
                    hasSearched = true
                )
            }
        }
    }

    fun performSearch(query: String) {
        val trimmedQuery = query.trim()
        if (trimmedQuery.length < 1) return

        // 手动搜索时添加到历史记录
        viewModelScope.launch {
            searchHistoryRepository.addSearchTerm(trimmedQuery)
            performRealtimeSearch(trimmedQuery)
        }
    }

    fun clearSearchHistory() {
        viewModelScope.launch {
            searchHistoryRepository.clearHistory()
        }
    }

    fun clearErrorMessage() {
        _uiState.update { it.copy(errorMessage = null) }
    }
}